<?php

class Vlib_Mailer {
    
    const MAIL_FORMAT_HTML = "html";
    const MAIL_FORMAT_TEXT = "text";
    
    protected $options;
    protected $logger;
    
    public function __construct($options = array()) {
        // if configuration array is not exists, using configuration from application
        // config file (application.php)
        if (!$options) {
            $appConf = Vlib_Config::getConfig();
            $mailSetting = $appConf[APPLICATION_ENV]['mail'];
            $this->options = array(
                'mail_server' => $mailSetting['mail_server'],
                'mail_server_type' => $mailSetting['mail_server_type'],
                'mail_charset' => $mailSetting['mail_charset'],
                'mail_encoding' => $mailSetting['mail_encoding'],
                'mail_smtp_auth' => $mailSetting['mail_smtp_auth'],
                'mail_smtp_auth_user' => $mailSetting['mail_smtp_auth_user'],
                'mail_smtp_auth_pwd' => $mailSetting['mail_smtp_auth_pwd'],
                'mail_from_address' => $mailSetting['mail_from_address'],
                'mail_from_name' => $mailSetting['mail_from_name'],
                'mail_port' => $mailSetting['mail_port'],
                'mail_format' => $mailSetting['mail_format'],
            );
        // using external configuration setting
        } else {
            $this->options = $options;
        }
        
        // initialize logger
        $this->logger = Vlib_Logger::getInstance();
        
        // initialize SMTP transport
        $this->initSmtpTransport();
    }
    
    public function setOptions($options = array()) {
        $this->options = $options;
        $this->initSmtpTransport();
        return $this;
    }
    
    public function getOptions() {
        return $this->options;
    }
    
    /**-----------------------------------------------------------------------------
     * @desc initialize SMTP transport for Zend_Mail
     * 
     * @author Tuyendn<tuyendn@vnext.vn>
     *------------------------------------------------------------------------------*/
    public function initSmtpTransport() {
        $this->logger->debugIn();
        if (!$this->options) return;
        try {
            $config = array(
                    'auth' => $this->options['mail_smtp_auth'],
                    'username' => $this->options['mail_smtp_auth_user'],
                    'password' => $this->options['mail_smtp_auth_pwd'],
                    'port' => $this->options['mail_port'],
            );
            
            // login with ssl
            if ($this->options['mail_server_use_ssl']) $config['ssl'] = 'ssl';
            
            $transport = new Zend_Mail_Transport_Smtp(
                $host = $this->options['mail_server'], 
                $config   
            );
            Zend_Mail::setDefaultFrom($this->options['mail_from_address'], $this->options['mail_from_name']);
            Zend_Mail::setDefaultTransport($transport);
        } catch (Zend_Exception $e) {
            $this->logger->error($e->getMessage());
        }
        $this->logger->debugOut();
        return $transport;
    }
    
     /**-----------------------------------------------------------------------------
     * @desc send a email
     * 
     * @author Tuyendn<tuyendn@vnext.vn>
     *------------------------------------------------------------------------------*/
    public function send($subject, $body, $arrfrom, $arrTo, $arrCc = array(), $arrBcc = array(), $arrAttachment = array()) {
        $this->logger->debugIn();
        try {
            // Test connect to server smtp if don't login
            $connectFail = false;
            if($this->options['mail_smtp_auth'] != 'login'){
                try{
                    $aryConfig = array();
                    if($this->options['mail_server_use_ssl'] == 1)
                            $aryConfig['ssl'] = 'ssl';
                    $smtp = new Zend_Mail_Protocol_Smtp($this->options['mail_server'], $this->options['mail_port'], $aryConfig);
                    if($smtp)
                        $smtp->connect();
                    else
                        $connectFail = true;
                }catch(Zend_Mail_Protocol_Exception $ex){
                    $this->logger->error($ex->getMessage());
                    $connectFail = true;
                }
            }
            if($connectFail == true){
                $this->logger->debugOut();
                return false;
            }
            // Init zend mail
            $mail = new Zend_Mail($this->options['mail_charset']);
            $mail->setFrom($arrfrom['mail'], $arrfrom['name']);
            
            // set mail to
            foreach ($arrTo as $arr) {
                $mail->addTo($arr['mail'], $arr['name']);
            }
            
            // set mail cc
            if ($arrCc) {
                foreach ($arrCc as $arr) {
                    $mail->addCc($arr['mail'], $arr['name']);
                }
            }
            
            // set mail bcc
            if ($arrBcc) {
                foreach ($arrBcc as $arr) {
                    $mail->addBcc($arr['mail'], $arr['name']);
                }
            }
            
            // set mail subject
            $mail->setSubject($subject);

            // set mail format
            if ($this->options['mail_format'] == self::MAIL_FORMAT_HTML) {
                $body = ln2br($body);
                $mail->setBodyHtml($body, $this->options['mail_charset'], Zend_Mime::ENCODING_8BIT);
            } else {
                $mail->setBodyText($body, $this->options['mail_charset'], Zend_Mime::ENCODING_8BIT);
            }
            
            // set mail attachment
            if ($arrAttachment) {
                $isFileExists = false;
                foreach ($arrAttachment as $attachment) {
                    if (file_exists($attachment['file'])) {
                        $content = file_get_contents(trim($attachment['file']));
                        $at = new Zend_Mime_Part($content);
                        $at->filename = $attachment['name'] ? trim($attachment['name']) : basename($attachment['file']);
                        $at->disposition = Zend_Mime::DISPOSITION_ATTACHMENT;
                        $at->encoding = Zend_Mime::ENCODING_BASE64;
                        $at->type = trim($attachment['mime_type']);
                        $mail->addAttachment($at);
                        $isFileExists = true;
                    }
                }
                if ($isFileExists) {
                    $mail->setType(Zend_Mime::MULTIPART_RELATED);
                }
            }

            return $mail->send();
        } catch (Zend_Mail_Exception $e) {
            $this->logger->error($e->getMessage());
        }
        $this->logger->debugOut();
        return false;
    }
    
    
}